package com.boboPlanet.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

/**
 * @Description: TODO
 * @Author: mis_wu
 * @Date: 2022/7/16
 * 重置bootstrap.properties文件编码
 * 需要在spring.factories中重新加载PropertySourceLoader配置
 * META-INF中：
 * #org.springframework.boot.env.PropertySourceLoader=/\
 * #  com.gateway.component.UnicodePropertySourceLoader
 **/
@Component
public class UnicodePropertySourceLoader implements PropertySourceLoader {

    Logger logger = LoggerFactory.getLogger(UnicodePropertySourceLoader.class);

    @Override
    public String[] getFileExtensions() {
        return new String[]{"properties", "xml"};
    }

    @Override
    public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
        Properties properties = getProperties(resource);
        if (!properties.isEmpty()) {
            logger.info("properties start 重新设置配置文件编码");
            PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource(name, properties);
            return Collections.singletonList(propertiesPropertySource);
        }
        return Collections.emptyList();
    }

    private Properties getProperties(Resource resource) {
        Properties properties = new Properties();
        try (InputStream inputStream = resource.getInputStream()) {
            properties.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        } catch (IOException e) {
            logger.error("Load resource inputStream failed.", e);
        }
        return properties;
    }
}
